import { message } from "antd"
import { history } from "umi";
import qs from "querystring"
// 请求中进行处理
function checkStatus(res) {
    if (200 <= res.status <= 300) {
        return res;
    }
    message.error(`网络请求错误,${res.status}`);
    throw new Error(res.statusText);
}

// 网络请求成功
async function successCode(res) {
    const data = await res.clone().json();
    if (data.code !== 0) {
        message.error(`${data.msg},状态码${data.code}`);
        history.push("/users/login");
        localStorage.clear();
    }
    return res;
}
//- 错误处理函数
const handlerError = (error) => {
    if (error instanceof TypeError) {
        message.error(`网络请求失败了${error}`);
    }
    return {
        code: -1,
        data: false,
    };
};

class Http {
    static staticFetch(url = "", option = "") {
        url = ("/api" + url);
        let defaultOption = {
            mode: "cors",
            headers: {
                "Authorization": localStorage.getItem("token") || null,
            },
        };
        if (option.method === "PUT" || option.method === "POST") {
            defaultOption.headers["Content-Type"] = 'application/json;charset=utf-8';
        }
        const newOptions = { ...defaultOption, ...option };
        return fetch(url, newOptions)
            .then(checkStatus)
            .then(successCode)
            .then(res => {
                const token = res.headers.get("Authorization");
                token && localStorage.setItem("token", token);
                return res.json();
            })
            .catch(handlerError);
    }
    // PUT请求
    put(url, params = {}, options = {},) {
        const defaultOptions = {
            method: "PUT",
            body: JSON.stringify(params)
        }
        const newOptions = { ...defaultOptions, ...options };
        return Http.staticFetch(url, newOptions);
    }

    // POST请求
    post(url, params = {}, options = {}) {
        const defaultOptions = {
            method: "POST",
            body: JSON.stringify(params)
        }
        const newOptions = { ...defaultOptions, ...options };
        return Http.staticFetch(url, newOptions);
    }

    // GET请求
    get(url, option = {}) {
        option && (url = url + '?' + qs.stringify(option));
        const defaultOptions = {
            method: "GET",
            ...option
        }
        return Http.staticFetch(url, defaultOptions);
    }

    // DELETE请求
    delete(url, option = {}) {
        option && (url + '?' + qs.stringify(option));
        const defaultOptions = {
            method: "DELETE",
            ...option
        }
        return Http.staticFetch(url, defaultOptions);
    }
}

const fetchFn = new Http();

export default fetchFn;